const userModel = require('../models/user.js')
const md5 = require('blueimp-md5')

exports.get = (req, res, next) => {
	const {user} = req.session
	if ( ! user) {
		return res.status(401).json({
			error : 'Unauthorized'
		})
	}
	res.status(200).json(user)
}

exports.create = async (req, res, next) => {
	const body = req.body
	const user = await userModel.getUserByCondition('email', body.email)
	if ( ! user) {
		return res.status(404).json({
			error : 'Invaild email or password'
		})
	}
	if (md5(md5(body.password)) != user.password) {
		return res.status(404).json({
			error : 'Invaild email or password'
		})
	}
	req.session.user = user
	res.status(201).json(user)
}

exports.destroy = (req, res, next) => {
	delete req.session.user
	res.status(201).json({})
}
